package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.db.api.UserInfoApi;
import com.tanhua.dubbo.mongo.api.FriendApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate template;

    //联系人添加
    public void contacts(Long friendId) {

        //获得本人id
        Long userId = UserHolder.getUserId();

        //保存到friend表中
        friendApi.save(userId,friendId);

        //注册到环信中
        template.addContact("hx"+userId,"hx"+friendId);


    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        //根据本人id查询所有好友数据
        List<Friend> list =friendApi.findFriends(userId,page,pagesize);

        List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);

        //获得用户数据表
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);

        List<ContactVo> vos=new ArrayList<>();
        for (Friend friend : list) {

            UserInfo userInfo = map.get(friend.getFriendId());

            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }

        return new PageResult(page,pagesize,0l,vos);
    }

    //根据环信id查询用户信息
    public UserInfoVo userInfo(String huanxinId) {

        String str = huanxinId.replaceAll("HX", "");
        Long id = Long.valueOf(str);

        UserInfo userInfo= userInfoApi.findById(id);

        UserInfoVo vo=new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);
        if (userInfo.getAge()!=null){
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }
}
